package it.sportingnola.soccernotes;

import it.sportingnola.soccernotes.adapter.GoalAdapter;
import it.sportingnola.soccernotes.listener.TeamGoalItemListener;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class GoalEdit extends AbstractSoccerActivity {
    private Spinner playerSpinner;
    private Spinner teamSpinner;
    private EditText idGoalText;
    private EditText timeText;
    private CheckBox isOwnGoal;
    private CheckBox isPenalty;
    private Spinner halfSpinner;
    private ListView griglia;
    private TextView titleFormText;
    private final String[] fromList=new String[]{Const.Goals.KEY_TEAM, Const.Goals.KEY_NAME_PLAYER,
	Const.Goals.KEY_MIN, Const.Goals.KEY_HALF };
    private final int[] toList=new int[]{R.id.team_goal_old, R.id.player_old, R.id.min_old, R.id.half_old };
    private final String[] fromPlSp=new String[]{Const.Players.KEY_NAME };
    private final int[] toPlSp=new int[]{android.R.id.text1 };

    @Override
    public void cancella(View view) {
	String rowId=idGoalText.getText().toString();
	if ( ! "".equals(rowId)) {
	    dbHelper.cancellaGoal(Long.parseLong(rowId));
	    Toast toast=Toast.makeText(this, getString(R.string.goal_deleted), Toast.LENGTH_SHORT);
	    toast.show();
	    fillData();
	}
	resetField();
    }

    public void createAndSetPlayerAdapter(int team) {
	int squadra=team;
	if (isOwnGoal.isChecked()) {
	    squadra=(squadra == Const.HOME_TEAM) ? Const.FOREIGN_TEAM : Const.HOME_TEAM;
	}
	Cursor playerCur=dbHelper.getAllPlayers(cronaca, squadra, false, true);
	startManagingCursor(playerCur);
	SimpleCursorAdapter playerAdapter=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item,
	    playerCur, fromPlSp, toPlSp);
	playerSpinner.setAdapter(playerAdapter);
    }

    @Override
    public void doLeftSwipeAction() {
	editCard(null);
    }

    @Override
    public void doRigthSwipeAction() {
	Intent i=new Intent(this, NoteEdit.class);
	i.putExtra(Const.Cronache.KEY_ROWID, cronaca);
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, 0);
	startActivityForResult(i, SoccerNotes.ACTIVITY_EDIT);
    }

    @Override
    protected void fillData() {
	Cursor sc=dbHelper.cercaGoal(cronaca);
	startManagingCursor(sc);
	GoalAdapter goalAdapter=new GoalAdapter(this, R.layout.goal_row, sc, fromList, toList);
	griglia.setAdapter(goalAdapter);
    }

    public Spinner getPlayerSpinner() {
	return playerSpinner;
    }

    @Override
    protected void performSetContentView() {
	setContentView(R.layout.goal_edit);
    }

    @Override
    protected void performSetTitle() {
	setTitle(getText(R.string.goals));
    }

    /**
     * Inizializza i campi presenti nella View
     */
    @Override
    protected void prepareFields() {
	titleFormText=(TextView) GoalEdit.this.findViewById(R.id.form_goal);
	idGoalText=(EditText) findViewById(R.id.id_goal);
	isPenalty=(CheckBox) findViewById(R.id.is_penalty);
	isOwnGoal=(CheckBox) findViewById(R.id.is_own);
	isOwnGoal.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View v) {
		int squadra_selected=teamSpinner.getSelectedItemPosition();
		int squarda=squadra_selected;
		// In caso di autogol vanno caricati i giocatori dell'altra squadra
		if (isOwnGoal.isChecked()) {
		    squarda=(squadra_selected == Const.HOME_TEAM) ? Const.FOREIGN_TEAM : Const.HOME_TEAM;
		}
		Cursor playerCur=GoalEdit.this.dbHelper.getAllPlayers(cronaca, squarda, false, true);
		SimpleCursorAdapter playerAdapter=new SimpleCursorAdapter(GoalEdit.this,
		    android.R.layout.simple_spinner_dropdown_item, playerCur, new String[]{Const.Players.KEY_NAME },
		    new int[]{android.R.id.text1 });
		playerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		playerSpinner.setAdapter(playerAdapter);
		if (isOwnGoal.isChecked()) {
		    isPenalty.setChecked(false);
		    isPenalty.setEnabled(false);
		}
		else {
		    isPenalty.setEnabled(true);
		}
	    }
	});
	playerSpinner=(Spinner) findViewById(R.id.player_goal);
	teamSpinner=(Spinner) findViewById(R.id.team_goal);
	ArrayAdapter<CharSequence> teamAdapter=new ArrayAdapter<CharSequence>(this,
	    android.R.layout.simple_spinner_dropdown_item);
	teamAdapter.add(team1Name);
	teamAdapter.add(team2Name);
	teamSpinner.setAdapter(teamAdapter);
	TeamGoalItemListener teamListener=new TeamGoalItemListener(this);
	teamSpinner.setOnItemSelectedListener(teamListener);
	halfSpinner=(Spinner) findViewById(R.id.half);
	ArrayAdapter<CharSequence> halfAdapter=ArrayAdapter.createFromResource(this, R.array.halfs,
	    android.R.layout.simple_spinner_dropdown_item);
	halfSpinner.setAdapter(halfAdapter);
	timeText=(EditText) findViewById(R.id.min);
	griglia=(ListView) findViewById(R.id.gridview);
	griglia.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Cursor c=GoalEdit.this.dbHelper.recuperaGoal(id);
		startManagingCursor(c);
		if (c.moveToFirst()) {
		    GoalEdit.this.titleFormText.setText(getString(R.string.edit_goal));
		    GoalEdit.this.halfSpinner.setSelection(c.getInt(c.getColumnIndex(Const.Goals.KEY_HALF)));
		    GoalEdit.this.idGoalText.setText(Long.toString(id));
		    GoalEdit.this.timeText.setText(c.getString(c.getColumnIndex(Const.Goals.KEY_MIN)));
		    boolean is_pen=c.getInt(c.getColumnIndex(Const.Goals.KEY_IS_PENALTY)) == 1;
		    GoalEdit.this.isPenalty.setChecked(is_pen);
		    boolean is_auto=c.getInt(c.getColumnIndex(Const.Goals.KEY_IS_AUTO)) == 1;
		    GoalEdit.this.isOwnGoal.setChecked(is_auto);
		    // HACK forzo il teamListener creando un cambio di team "finto"
		    // le successive 4 righe servono a risolvere il bug numero 19
		    // da sostituire con una soluzione più egante
		    // come forzare il cambio solo quando necessario
		    int actTeam=c.getInt(c.getColumnIndex(Const.Cards.KEY_TEAM));
		    int fintoTeam=actTeam == Const.HOME_TEAM ? Const.FOREIGN_TEAM : Const.HOME_TEAM;
		    GoalEdit.this.teamSpinner.setSelection(fintoTeam, false);
		    GoalEdit.this.teamSpinner.setSelection(actTeam, false);
		    GoalEdit.this.playerSpinner.setSelection(Util.getPlayerPos(
			c.getLong(c.getColumnIndex(Const.Goals.KEY_PLAYER)), GoalEdit.this.playerSpinner.getAdapter()));
		}
	    }
	});
    }

    @Override
    protected void resetField() {
	halfSpinner.setSelection(0);
	teamSpinner.setSelection(0);
	isOwnGoal.setChecked(false);
	isPenalty.setChecked(false);
	playerSpinner.setSelection(0);
	idGoalText.setText("");
	timeText.setText("");
	titleFormText.setText(getString(R.string.new_goal));
    }

    @Override
    public void salva(View view) {
	saveState();
	resetField();
	fillData();
    }

    @Override
    protected void saveState() {
	long player=playerSpinner.getSelectedItemId();
	String rowId=idGoalText.getText().toString();
	boolean isAuto=isOwnGoal.isChecked();
	boolean isRigore=isPenalty.isChecked();
	int team=teamSpinner.getSelectedItemPosition();
	int half=halfSpinner.getSelectedItemPosition();
	String min=timeText.getText().toString();
	if (rowId.equals("")) {
	    dbHelper.insertGoal(player, team, half, min, cronaca, isAuto, isRigore);
	}
	else {
	    dbHelper.updateGoal(Long.parseLong(rowId), player, team, half, min, cronaca, isAuto, isRigore);
	}
	Toast toast=Toast.makeText(this, getString(R.string.just_saved), Toast.LENGTH_SHORT);
	toast.show();
    }
}
